<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="showDialog"
    width="30%"
    class="edit-dialog edit-container"
  >
    <el-form :model="petForm" ref="petForm" label-width="120px" :rules="rules">
      <el-form-item label="出身背景:" prop="background">
        <TemplateSelect
          :selectValue.sync="petForm.background"
          :selectList="options.background"
          placeholder="请选择出身情况"
        ></TemplateSelect>
      </el-form-item>
      <el-form-item label="宠物生日:">
        <el-col :span="11">
          <el-form-item prop="birthday">
            <el-date-picker
              type="date"
              placeholder="选择日期"
              v-model="petForm.birthday"
              style="width: 100%"
              :picker-options="timeChange"
              value-format="yyyy-MM-ddT00:00:00"
            >
              ></el-date-picker
            >
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="笼子名称:" prop="cageId">
        <TemplateSelect
          :selectValue.sync="petForm.cageId"
          :selectList="options.cageId"
          placeholder="请选择笼子名称"
        ></TemplateSelect>
      </el-form-item>
      <el-form-item label="毛发特点:" prop="hairFeature">
        <TemplateSelect
          :selectValue.sync="petForm.hairFeature"
          :selectList="options.hairFeature"
          placeholder="请选择毛发特点"
        ></TemplateSelect>
      </el-form-item>
      <el-form-item label="毛发长度:" prop="hairLength">
        <TemplateSelect
          :selectValue.sync="petForm.hairLength"
          :selectList="options.hairLength"
          placeholder="请选择毛发长度"
        ></TemplateSelect>
      </el-form-item>
      <el-form-item label="狗狗名字:" prop="name">
        <el-input v-model="petForm.name"></el-input>
      </el-form-item>
      <el-form-item label="来源:" prop="origin">
        <TemplateSelect
          :selectValue.sync="petForm.origin"
          :selectList="options.origin"
          placeholder="请选择来源"
        ></TemplateSelect>
      </el-form-item>
      <el-form-item label="狗狗性格:" prop="personality">
        <TemplateSelect
          :selectValue.sync="petForm.personality"
          :selectList="options.personality"
          placeholder="请选择狗狗性格"
        ></TemplateSelect>
      </el-form-item>

      <el-form-item label="图片:" prop="pictures">
        <el-upload
          :action="host"
          list-type="picture"
          multiple
          :limit="limit"
          name="pictures"
          ref="my-upload"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :on-exceed="handleExceed"
          :on-success="handleSuccess"
          :file-list="fileList"
        >
          <div class="pic-uploader">
            <template v-if="fileList.length >= 1">
              <div
                class="maskbox"
                v-for="(item, index) in fileList"
                :key="item + index"
              >
                <img :src="item.url" class="pic" />
                <div class="mask">
                  <button @click.stop="deleteImg($event, index)">删除</button>
                </div>
              </div>
            </template>
            <img v-else src="@/assets/img/picture.png" class="default-pic" />
          </div>
          <el-button class="redBtn dpb borderBtn" type="warning"
            >选择图片</el-button
          >
        </el-upload>
      </el-form-item>
      <el-form-item class="message">
        <span>提示：单张图片大小不要超过 5 MB</span>
      </el-form-item>
      <el-form-item label="狗狗性别:" prop="sex">
        <TemplateSelect
          :selectValue.sync="petForm.sex"
          :selectList="options.sex"
          placeholder="请选择狗狗性别"
        ></TemplateSelect>
      </el-form-item>
      <el-form-item label="狗狗体型:" prop="size">
        <TemplateSelect
          :selectValue.sync="petForm.size"
          :selectList="options.size"
          placeholder="请选择狗狗体型"
        ></TemplateSelect>
      </el-form-item>

      <el-form-item label="狗狗绝育情况:" prop="sterilization">
        <TemplateSelect
          :selectValue.sync="petForm.sterilization"
          :selectList="options.sterilization"
          placeholder="请选择狗狗绝育情况"
        ></TemplateSelect>
      </el-form-item>
      <el-form-item label="小院id:" prop="yardId">
        <el-input
          v-model.number="petForm.yardId"
          :readonly="true"
          class="readOnlyInput"
        ></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import TemplateSelect from "@/components/template-el-select/TemplateSelect.vue"
import editMixin from "./mixins/editMixin.js"
export default {
  mixins: [editMixin],
  props: {
    addPetDialog: {
      required: true,
      default: ""
    },
    dialogTitle: {
      type: String,
      required: true,
      default: "编辑"
    }
  },
  computed: {
    showDialog: {
      get() {
        return this.addPetDialog
      },
      set(val) {
        this.$emit("update:addPetDialog", val)
        this.resetForm("petForm")
      }
    }
  },
  watch: {
    showDialog(newName) {
      if (newName) {
        this.cageNames()
      }
    }
  },
  data() {
    return {
      host: process.env.VUE_APP_baseUrl + "/dog-manage/upload",
      fileList: [], //返显要上传的图片数组
      file: "", //暂存图片文件
      limit: 10, //限制选择的图片数量
      timeChange: {
        disabledDate(time) {
          return time.getTime() > Date.now()
          //选择时间范围
        }
      },
      petForm: {
        background: "",
        birthday: "",
        cageId: "",
        hairFeature: "",
        hairLength: "",
        name: "",
        origin: "",
        personality: "",
        pictures: [],
        sex: "",
        size: "",
        sterilization: "",
        yardId: "1"
      }
    }
  },
  components: {
    TemplateSelect
  },
  methods: {
    // 图片上传成功回调
    handleSuccess(res, file) {
      this.fileList.push(file) //将上传的图片预显在页面(本地)
      if (res.code == "0") {
        this.petForm["pictures"].push(res.data[0]) //将接口返回的图片地址存到表单
      }
    },
    //图片上传的校验-小于5M
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 5
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 5MB!")
      }
      return isLt2M
    },
    //上传图片超出数量的处理函数
    handleExceed() {
      this.$message.warning(
        `当前限制选择${this.limit}张图片，鼠标移动到图片上可删除现有图片`
      )
    },
    // 删除图片
    deleteImg(event, index) {
      this.fileList.splice(index, 1)
      this.petForm["pictures"].splice(index, 1)
      event.preventDefault()
    },
    //确定修改/新增
    submitForm() {
      this.$refs["petForm"].validate(valid => {
        if (valid) {
          switch (this.dialogTitle) {
            case "新增狗狗":
              this.newDog()
              break
            default:
              this.editDog()
              break
          }
        } else {
          console.log("error submit!!")
          return false
        }
      })
    },
    //新增狗狗信息
    async newDog() {
      const that = this
      let params = {
        ...this.petForm
      }
      try {
        await that.$http.post("/dog-manage/newDog", params, "json")
        that.$message({
          message: "新增狗狗成功",
          type: "success"
        })
        this.resetForm("petForm")
        this.showDialog = false
        this.$emit("loadData")
      } catch (err) {
        console.log("报错了：", err)
      }
    },
    //编辑狗狗
    async editDog() {
      const that = this
      let params = {
        ...this.petForm
      }
      try {
        await that.$http.put("/dog-manage/modifyOneDog", params)
        that.$message({
          message: "修改信息成功",
          type: "success"
        })
        that.resetForm("petForm")
        that.showDialog = false
        that.$emit("loadData")
      } catch (err) {
        console.log("报错了：", err)
      }
    },
    //获取当前小院的笼子
    async cageNames() {
      const that = this
      let params = {
        yardId: "1"
      }
      try {
        const res = await that.$http.get("/cage/cageNames", params, "json")
        let newArr = res.data
        newArr.forEach(element => {
          element["label"] = element.name
          element["value"] = element.id
        })
        that.options.cageId = newArr
      } catch (err) {
        console.log("报错了：", err)
      }
    },
    //重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.fileList = []
    },
    cancel() {
      this.resetForm("petForm")
      this.showDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
.edit-container {
  width: 100%;
  .pic-uploader {
    // width: 100%;
    display: flex;
    flex-wrap: wrap;
    .maskbox {
      margin-bottom: 20px;
    }
  }
  .dpb {
    display: block;
  }
  .maskbox {
    position: relative;
    .pic {
      width: 120px;
      height: 120px;
      border-radius: 4px;
      margin-right: 15px;
    }
    .default-pic {
      width: 46px;
      height: 46px;
    }
    &:hover .mask {
      visibility: visible;
    }
    .mask {
      visibility: hidden;
      position: absolute;
      border-radius: 4px;
      height: 120px;
      width: 120px;
      top: 0;
      left: 0;
      background: rgba(0, 0, 0, 0.6);
      display: flex;
      align-items: center;
      z-index: 10;
      > button {
        width: 100px;
        height: 32px;
        box-sizing: border-box;
        border: 1px solid #ffffff;
        border-radius: 4px;
        background: transparent;
        margin: 0 auto;
        font-size: 14px;
        font-weight: 400;
        color: #ffffff;
        line-height: 20px;
      }
    }
  }
}
.readOnlyInput /deep/.el-input__inner {
  background: rgba(161, 160, 160, 0.3);
  &:hover {
    cursor: pointer;
  }
}
</style>
